package com.zhuchang.self_rpc.test.democoding.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import jdk.nashorn.internal.ir.CallNode;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @Author RenPu
 * @Date 2022/2/10 15:42
 * @Version 1.0
 * @Description:  Netty实现群聊系统---客户端+心态检测客户端
 **/


public class GroupChatClientNetty {

    private String host;

    private int port;

    public GroupChatClientNetty(String host, int port) {
        this.host = host;
        this.port = port;
    }


    /**
     * Netty客户端启动方法
     */
    public void startClient(){
        NioEventLoopGroup eventLoopGroup=new NioEventLoopGroup();
        Bootstrap bootstrap=new Bootstrap();



        try {
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("encoder",new StringEncoder())
                                    .addLast("decoder",new StringDecoder())
                                    .addLast(new ClientNettyHandle());
                        }
                    });


            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync();
            Channel channel = channelFuture.channel();
            System.out.println("--------------"+channel.localAddress()+"-----------------");

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String s = scanner.nextLine();
                channel.writeAndFlush(s+"\r\n");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }


    }



    public static void main(String[] args) {
        GroupChatClientNetty groupChatClientNetty = new GroupChatClientNetty("127.0.0.1",4888);
        groupChatClientNetty.startClient();
    }



}
